<template>
  <basic-modal
    :modalOpt="modal"
    :footer="footer"
    :buttonText="['提交','取消']"
    @onMakeSure="onSubmit"
    @closeModal="closeModal"
  >
    <template>
      <batch-operat-btn
        v-if="editable"
        :isView="false"
        :addData="true"
        addText='选择商品'
        @onAddData="onAddData"
      >
        <template #cusBtn> </template>
      </batch-operat-btn>
      <div class="recordBox">
        <a-list-table
          :columns="columns"
          :inputNameObj="inputName"
          :tableData="listdata"
          :isSelecttion="false"
          :loading="loading"
          :scroll="{ y: null }"
          @onAction="onAction"
          @onChangeInput="onChangeInput"
        >
        </a-list-table>
      </div>
      <addGoodsModal
        ref="addGoodsModal"
        @onAddInfo="onAddInfo"
      />
    </template>
  </basic-modal>

</template>

<script>
import basicModal from '../common/basicModal'
import basicForm from '../common/basicForm'
import addGoodsModal from './addGoodsModal'
import aListTable from '@/views/app/biz/common/aListTable'
import batchOperatBtn from '@/views/app/biz/common/batchOperatBtn'
import { editOederGoods, getDetailByConditions, deleteGoodsInfo } from './purchaseOrder'

export default {
  components: {
    basicModal,
    basicForm,
    addGoodsModal,
    aListTable,
    batchOperatBtn
  },
  data () {
    return {
      footer: undefined,
      loading: false,
      modal: {
        modalVisible: false,
        modalTitle: '',
        modalWidth: '90vw',
        maxHeight: '80vh'
      },
      columns: [
        { title: '编码', dataIndex: 'standardCode', key: 'standardCode', align: 'center' },
        { title: '品名', dataIndex: 'productNameZh', key: 'productNameZh', align: 'center', },
        { title: '供应商名称', dataIndex: 'supplierName', key: 'supplierName', align: 'center' },
        // { title: '通用名', dataIndex: 'tongYongm', key: 'tongYongm', align: 'center' },
        { title: '订单号', dataIndex: 'purOrderNo', key: 'purOrderNo', align: 'center', },
        { title: '生产企业名称', dataIndex: 'manufacturerZh', key: 'manufacturerZh', align: 'center', },
        { title: '规格', dataIndex: 'spec', key: 'spec', align: 'center' },
        { title: '型号', dataIndex: 'model', key: 'model', align: 'center' },
        { title: '计量单位', dataIndex: 'measurement', key: 'measurement', align: 'center' },
        { title: '单品含税价', dataIndex: 'iunitprice', key: 'iunitprice', align: 'center', scopedSlots: { customRender: 'iunitprice' } },
        { title: '采购数量', dataIndex: 'num', key: 'num', align: 'center', scopedSlots: { customRender: 'num' } },
        {
          title: '操作',
          dataIndex: 'action',
          width: 100,
          key: 'operation',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      inputName: [
        { name: 'iunitprice', type: 'text', placeholder: '价格' },
        { name: 'num', type: 'number', placeholder: '数量' },
      ],
      listdata: [],
      q_formDatas: {
        purOrderPid: null,
      },
      orgList: [],
      changeList: [],
      editable: true,
      pid: '',
      sysSeq: 0,
      loadings: false,
      order: {},
      pagination: {
        current: 1,
        pageSize: 10000,
        total: 1,
      },
    }
  },
  computed: {},
  mounted () { },
  methods: {
    // 新增按钮 点击了新增
    addModal () {
      console.log('点击了新增')
      this.modal.modalVisible = true
      this.modal.modalTitle = '新增证照'
    },
    // 编辑按钮 点击了编辑
    editModal (val) {
      console.log('点击了编辑')
      this.order = val
      this.listdata = []
      this.changeList = []
      this.orgList = []
      this.q_formDatas.purOrderPid = val.pid
      this.getList(this.q_formDatas)
      this.modal.modalVisible = true
      this.modal.modalTitle = '修改采购单商品'
    },
    // 关闭模态详细框
    closeModal () {
      this.modal.modalVisible = false
      this.$emit('close')
    },
    // 保存成功关闭模态详细框
    closeModal2 () {
      this.modal.modalVisible = false
      this.$emit('ok')
    },
    //点击选择商品
    onAddData () {
      this.$refs.addGoodsModal.addModal(this.pid)
    },
    // 子modal提交过来的信息
    onAddInfo (datas) {
      let newArr = []
      outloop:
      for (let item of datas) {
        for (let items of this.listdata) {
          if (items.purProdPid == item.pid) {
            this.$message.warn({ content: item.supplierOrgName + '的商品：' + item.productNameZh + '已添加，请勿重复添加' })
            newArr = []
            break outloop;
          }
        }
        newArr.push({
          key: item.pid,
          action: ['删除'],
          pid: '',
          sysSeq: 0,
          purOrderPid: this.order.pid,
          purOrderNo: this.order.purOrderNo,
          supplierName: item.supplierOrgName,
          purProdPid: item.pid,
          productNameZh: item.productNameZh,
          model: item.model,
          standardCode: item.standardCode,
          supplierOrgCode: item.supplierOrgCode,
          spec: item.spec,
          manufacturerZh: item.manufacturerZh,
          measurement: item.measurement,
          num: item.minPackageNum ? item.minPackageNum : 1,
          iunitprice: item.price,
        })
      }
      console.log(newArr)
      if (newArr.length) {
        this.listdata.push.apply(this.listdata, newArr);
        this.changeList = this.listdata
        this.$refs.addGoodsModal.closeModal()
      }

      console.log(this.changeList)
    },
    //修改列表信息aList为修改的记录
    onChangeInput (aList) {
      const listindex = this.changeList.findIndex(item => item.key == aList.key)
      console.log(listindex);
      if (listindex + 1) {
        this.changeList[listindex] = aList
      } else {
        this.changeList.push(aList)
      }
      console.log(this.changeList);
    },
    // 模态详细框提交按钮
    onSubmit () {
      if (this.changeList.length) {
        let listdata = JSON.parse(JSON.stringify(this.changeList))
        for (const item of listdata) {
          delete item.action;
        }
        this.saveObjInfo(listdata)
      } else {
        this.$message.warn({ content: '未修改信息', duration: 2 })
      }
    },
    // 保存详细信息
    async saveObjInfo (val) {
      console.log(val)
      let key = 'updatable'
      this.$message.loading({ content: '提交中', key, duration: 0 })
      let res = await editOederGoods(val)
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        this.$message.success({ content: '提交成功', key, duration: 3 })
        this.closeModal2()
      } else {
        this.$message.error({ content: '提交失败,请稍后再试', key, duration: 3 })
      }
    },
    // 初始化查询时的数据列表
    async getList (params) {
      console.log('请求列表时传入的数据', params)
      this.loading = true
      let listdata = []
      let res = ''
      res = await getDetailByConditions(params, this.pagination)
      this.loading = false
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        const resdata = res.data
        this.orgList = res.data
        for (let item of resdata) {
          listdata.push({
            key: item.pid,
            action: ['删除'],
            ...item
          }
          )
        }
        this.listdata = listdata
      } else {
        this.listdata = []
      }
    },
    onAction (text, record, index) {
      console.log(text, record, index)
      //deleteGoodsInfo
      if (text == '删除') {
        let inOrgData = this.orgList.findIndex(item => item.purProdPid == record.purProdPid)
        console.log(inOrgData);
        if (inOrgData + 1) {
          this.showConfirm(record, '1', index)
        } else {
          let delIndex = this.changeList.findIndex(item => item.purProdPid == record.purProdPid)
          if (delIndex + 1) {
            this.changeList.splice(delIndex, 1)
          }
          this.listdata.splice(index, 1)
        }

      }
    },
    showConfirm (val, type, index) {
      let datas = []
      if (type == '1') {
        datas[0] = val
      } else {
        datas = val
      }
      const that = this;
      this.$confirm({
        title: '是否确认删除？',
        content: '此数据已存在于数据库，该操作将删除数据库中的数据。',
        onOk () {
          let reqArr = []
          let key = 'self'
          for (const item of datas) {
            reqArr.push(that.pushGoods(item))
          }
          return Promise.all(reqArr).then(res => {
            console.log(res);
            for (const item of res) {
              console.log(item);
              if (item && item.code && item.code === 'C1' && item.data) {
                let delIndex = that.changeList.findIndex(item => item.purProdPid == val.purProdPid)
                if (delIndex + 1) {
                  that.changeList.splice(delIndex, 1)
                }
                that.listdata.splice(index, 1)
                that.$message.success({ content: '删除成功', duration: 3 })
              } else {
                that.$message.error({ content: '删除失败，原因：' + item.message, duration: 3 })
              }
            }
            // that.handleModalSaveOk()
          }).catch(err => {
            that.$message.error({ content: '操作出错:' + err, duration: 3 })
          })
        },
        onCancel () { },
      });
    },
    async pushGoods (val) {
      let res = await deleteGoodsInfo(val)
      return res
    },
  },
}
</script>

<style>
</style>